package Engine.Model
{
	import Engine.Manager.EngineManager;
	
	import Interface.Model.IJsConnection;
	
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.net.sendToURL;
	import flash.utils.Timer;
	import flash.utils.setTimeout;
	
	public class JsConnection implements IJsConnection
	{
		private var isJsReady:Boolean = false;
		private static const MAX_CHECK_TIME:int = 10;
		private var currentTime:int = 0;
		
		
		public function JsConnection()
		{
			if (ExternalInterface.available)
				this.checkReady();
			else
				EngineManager.logPrint.printLog("Flash不处于浏览器中,或者浏览器不能通信");
		}
		
		private function onCheckReady():void
		{
			this.currentTime ++;
			EngineManager.logPrint.printLog("正在与浏览器建立连接:",this.currentTime);
			if(this.currentTime == MAX_CHECK_TIME)
			{
				EngineManager.logPrint.printLog("与浏览器建立连接失败"); 
			}
			else
			{
				this.checkReady();
			}
		}
		
		private function checkReady():void
		{
			if(ExternalInterface.call("isReady"))
			{
				this.jsIsReady();
			}
			else
				setTimeout(this.onCheckReady,1000)
		}
		
		private function jsIsReady():void
		{
			EngineManager.logPrint.printLog("与浏览器建立连接成功");
			this.isJsReady = true;
		}
		
		//注册一个函数给JS调用
		public function addJSCallFunction(funcName:String,funcAddr:Function):void
		{
			if (ExternalInterface.available)
				ExternalInterface.addCallback(funcName,funcAddr);
		}
		
		
		//调用一个JS的函数
		public function callJSFunction(funcName:String):Object
		{
			return ExternalInterface.call(funcName);
		}
		
	}
}